<template>
  <fixed-pagination>
    <div class="center">
      <template v-if="detailInfo.orderStatus > 1">
        <div v-if="detailInfo && detailInfo.orderStatus && detailInfo.orderStatus === 7 && isShowScoreTip" :class="{ 'score-tip-mobile': showMobilePage }" :style="{ 'left': String(scoreTipLeft) + 'px' }" class="score-tip">
          <i class="el-icon-warning" />
          <span>订单已完成请为订单打分</span>
          <i class="el-icon-close icon" @click="closeScoreTip"/>
        </div>
        <el-rate v-if="score" v-model="score" :show-score="!!score" :colors="{ 5: '#FFBC3D' }" disabled score-template="{value}"/>
        <el-button type="primary" size="small" class="global-plain-btn" @click="toScoreList">评分</el-button>
      </template>
      <template v-if="detailInfo.orderStatus === 0">
        <!-- 对冲单不能编辑 orderType(2) -->
        <el-button v-if="isEditAuth && detailInfo.orderType !== 2" type="primary" size="small" class="submit-btn" @click="toEdit">编辑订单</el-button>
      </template>
      <!-- 待发布 -->
      <template v-if="detailInfo.orderStatus === 1">
        <el-dropdown v-if="showMobilePage && (isPublishAuth || hasRouteAuth('crm:orderList:toBeAnnoEdit'))" style="margin-right: 10px;" trigger="click" class="mobile-btn-flex" placement="bottom">
          <el-button size="small">更多</el-button>
          <el-dropdown-menu slot="dropdown" style="padding: 0;">
            <!-- <el-dropdown-item v-if="isPublishAuth || isEditAuth" style="text-align: center" @click.native="revokeDialog({status: 0,message: '您的订单信息有误，请及时调整后提交'})">
              <div>撤回</div>
            </el-dropdown-item> -->
            <el-dropdown-item v-if="isPublishAuth" style="text-align: center" @click.native="toPublishDialog">
              <div>发布</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="isPublishAuth" style="text-align: center" @click.native="toSubmit">
              <div>保存</div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <template v-else>
          <!-- <el-button v-if="isPublishAuth || isEditAuth" type="danger" plain size="small" class="submit-btn" @click="revokeDialog({status: 0,message: '您的订单信息有误，请及时调整后提交'})">撤回</el-button> -->
          <el-button v-if="isPublishAuth" type="info" size="small" class="back-btn empty-btn-style" @click="toSubmit">保存</el-button>
          <el-button v-if="isPublishAuth" :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="toPublishDialog">发布</el-button>
          <el-button v-if="hasRouteAuth('crm:orderList:toBeAnnoEdit')" type="info" size="small" class="back-btn cancel-btn-style" @click="toEdit">编辑订单</el-button>
        </template>
      </template>
      <!-- 待核算 -->
      <!-- v2.8.8 取消待核算步骤 -->
      <!-- 待审批 -->
      <template v-if="detailInfo.orderStatus === 3">
        <el-dropdown v-if="showMobilePage && (isPublishAuth || isExamineAuth)" style="margin: 0 10px;" trigger="click" class="mobile-btn-flex" placement="bottom">
          <el-button size="small">更多</el-button>
          <el-dropdown-menu slot="dropdown" style="padding: 0;">
            <el-dropdown-item v-if="isExamineAuth || isPublishAuth" style="text-align: center" @click.native="revokeDialog({status: 1,message: '您有被退回待发布的订单'})">
              <div>撤回</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="isExamineAuth" style="text-align: center" @click.native="toExamineOrder">
              <div>审批</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="isExamineAuth" style="text-align: center" @click.native="toEdit">
              <div>编辑订单</div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <template v-else>
          <el-button v-if="isExamineAuth || isPublishAuth" type="danger" plain size="small" class="submit-btn" @click="revokeDialog({status: 1,message: '您有被退回待发布的订单'})">撤回</el-button>
          <el-button v-if="isExamineAuth" :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="toExamineOrder">审批</el-button>
          <el-button v-if="isExamineAuth" type="info" size="small" class="back-btn cancel-btn-style" @click="toEdit">编辑订单</el-button>
        </template>
      </template>
      <!-- 待封账 -->
      <template v-if="detailInfo.orderStatus ===4">
        <el-button v-if="isExamineAuth || isAllAdmin" type="danger" plain size="small" class="submit-btn" @click="revokeDialog({status: 3,message: '您有被退回待审批的订单'})">撤回</el-button>
      </template>
      <template
        v-if="detailInfo.isShowChange && isEditAuth && detailInfo.orderType !== 2 &&
      (detailInfo.orderStatus === 6 || detailInfo.orderStatus === 7) && hasRouteAuth('crm:orderList:add')">
        <el-button type="primary" size="small" class="submit-btn" @click="goChange">变更</el-button>
      </template>
      <el-button type="info" size="small" class="back-btn cancel-btn-style mobile-btn-flex" @click="toBack">返回列表</el-button>
    </div>
    <Dialog
      ref="publishDialogRef"
      :allDeptList="allDeptList"
      :btn1="'确认提交'"
      :btn2="'暂不提交'"
      summary="请确认是否发布订单"
      title="订单发布确认"
      tip="接收人请选择需要审批的人员：如销售经理"
      @handelOK="toPublish" />
    <Dialog
      ref="backDialogRef"
      :btn1="'确认'"
      :btn2="'取消'"
      :allDeptList="allDeptList"
      summary="请确认是否将订单撤回上一步"
      title="订单撤回确认"
      @handelOK="revoke" />
    <Dialog
      ref="submitDialogRef"
      :allDeptList="allDeptList"
      :summary="submitSummary"
      :btn1="'确认提交'"
      :btn2="'暂不提交'"
      title="订单提交确认"
      @handelOK="submitCost" />
    <Dialog
      ref="examineDialogRef"
      :allDeptList="allDeptList"
      :status="0"
      :btn1="'确认'"
      :btn2="'取消'"
      summary="请确认是否将订单撤回上一步"
      title="订单撤回确认"
      @handelOK="toExamine" />
  </fixed-pagination>
</template>

<script>
import { hasRouteAuth } from '@/utils/permission';
import { MessageBox } from 'element-ui';
// api
import { allDeptlist } from '@/api/select';
import { publishOrder, backOrder, submitCost, examineOrder } from '@/api/order';
// components
import Dialog from './dialog';
// util
import { handelDepartmentData } from '@/utils';
import ElMessage from '@/utils/message';
import { mapState } from 'vuex';

export default {
  components: { Dialog },
  props: {
    orderId: {
      type: String | Number,
      default: ''
    },
    isDisabledWithoutMicro: {
      type: Boolean,
      default: false
    },
    isDisabledMicro: {
      type: Boolean,
      default: false
    },
    detailInfo: {
      type: Object,
      default: () => {
        return {};
      }
    },
    score: {
      type: Number,
      default: 0
    },
    isShowScoreTip: {
      type: Boolean,
      default: false
    },
    scoreTipLeft: {
      type: Number,
      default: null
    },
    isLinkRequired: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      btnLoading: false,
      allDeptList: [],
      submitSummary: '',
      clientWidth: ''
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isDeptAuth() {
      // 当前登录的用户是否存在该条订单的部门中,或者协作部门中
      const item = this.detailInfo ? this.detailInfo : {};
      let departmentAuth = false;
      const departmentId = item.attributionMatrixId;
      let cooperationDepartmentIds = []; // 协作部门ID
      if (item.orderInfo.cooperationDepartment && item.orderInfo.cooperationDepartment.length) {
        cooperationDepartmentIds = item.orderInfo.cooperationDepartment.map(i => i.id);
      }
      const currentDeptIds = this.userInfo.currentDeptIds || []; // 当前部门的所有id，比如：用户部门是 研发部->产品组，那么当前部门就是产品组
      const topDeptIds = this.userInfo.topDeptIds || []; // 顶级部门的id列表，比如：用户部门是 研发部->产品组，那么顶级部门就是研发部
      const departmentAry = currentDeptIds.concat(topDeptIds);
      departmentAuth = departmentAry.some(i => {
        return (departmentId === i) || cooperationDepartmentIds.includes(i);
      });
      return departmentAuth;
    },
    isAllAdmin() { // 是否有全向权限
      // 拥有部门全向编辑（crm:orderList:adminEdit），当前登录的用户存在该条订单的部门中,或者协作部门中
      // 全向展示或全向编辑
      return hasRouteAuth('crm:orderList:admin') || (hasRouteAuth('crm:orderList:adminEdit') && this.isDeptAuth);
    },
    isPublishAuth() { // 发布权限
      /**
       * 发布权限 && （
       * 用户在该条订单的执行人中 ||
       * 用户为当前销售  ||
       * 部门全向编辑及部门符合要求 ||
       * 全向展示 ||
       * 如果执行人为空且部门符合要求）
       */
      if (this.userInfo.userName === '管理员') return true; // 管理员
      const item = this.detailInfo ? this.detailInfo : {};
      const orderOperator = item.orderInfo.orderOperator; // 执行人商务侧
      const isOperatorAuth = orderOperator ? orderOperator.some(i => {
        return i.id === this.userInfo.id;
      }) : false; // 是否是执行人商务侧
      const ResourceOperator = item.orderInfo ? item.orderInfo.orderResourceOperator : []; // 执行人资源侧
      const isResourceAuth = ResourceOperator ? ResourceOperator.some(i => {
        return i.id === this.userInfo.id;
      }) : false; // 是否是执行人资源侧
      const marketId = this.detailInfo ? this.detailInfo.clientInfo.marketId : '';
      const isSales = marketId === this.userInfo.id; // 是否销售

      // 如果没有执行人，则判断当前登录的用户存在该条订单的部门中,或者协作部门中
      const isNoOperator = !item.orderInfo.orderOperator || item.orderInfo.orderOperator.length === 0;

      return (isOperatorAuth || isResourceAuth || isSales || (isNoOperator && this.isDeptAuth) || this.isAllAdmin) && hasRouteAuth('crm:orderList:publish');
    },
    isExamineAuth() { // 审批权限
      return hasRouteAuth('crm:orderList:examine');
    },
    isEditAuth() {
      // 销售、执行人、协作部门 可编辑
      const item = this.detailInfo ? this.detailInfo : {};
      if (hasRouteAuth('crm:orderList:admin')) return true; // 全向展示

      let haveOrderOperator = false; // 当前登录的用户是否在该条订单的执行人中
      if (item.orderInfo.orderOperator) haveOrderOperator = item.orderInfo.orderOperator.some(i => i.id === this.userInfo.id);

      let haveOrderMarket = false; // 是否是当前销售
      if (item.clientInfo.marketId) haveOrderMarket = this.userInfo.id === item.clientInfo.marketId;

      let departmentAuth = false; // 拥有部门全向编辑，当前登录的用户存在该条订单的部门中,或者协作部门中
      const isNoOperator = !item.orderInfo.orderOperator || item.orderInfo.orderOperator.length === 0;
      if (hasRouteAuth('crm:orderList:adminEdit') || isNoOperator) {
        // 如果执行人为空，则这条订单的所有部门成员都可以编辑
        departmentAuth = this.isDeptAuth;
      }
      return haveOrderOperator || haveOrderMarket || departmentAuth;
    }
  },
  created() {
    // this.getAllDeptList();
  },
  methods: {
    hasRouteAuth,
    // 保存和保存草稿：草稿中、待发布
    toSubmit(isValidate = true) {
      this.$emit('toSubmit', { isValidate });
    },
    closeScoreTip() {
      this.$emit('closeScoreTip');
    },
    // 检验发布数据
    validateOrderInfo() {
      return new Promise((resolve, reject) => {
        const orderInfo = this.detailInfo.orderInfo || {};
        const publishInfo = this.detailInfo.publishInfo || {};
        // 无号单和多账号发布信息非必填
        if (![1, 2].includes(orderInfo.resourceType) && this.isLinkRequired) {
          if (!publishInfo.publishUrl) {
            ElMessage.error('请填写发布链接');
            reject(false);
            return;
          }
          if (!publishInfo.autoPick) {
            if (!publishInfo.publishRemark) {
              ElMessage.error('请填写发布文案');
              reject(false);
              return;
            }
            if (!publishInfo.attachment || publishInfo.attachment.length === 0) {
              ElMessage.error('请上传发布截图');
              reject(false);
              return;
            }
          }
        }
        resolve(true);
      });
    },
    // 发布：待发布
    toPublishDialog() {
      this.$emit('toSubmit', { isValidate: true, muted: true, loading: false }, this.publishFn);
    },
    publishFn() {
      this.validateOrderInfo().then(() => {
        const params = {
          id: this.orderId,
          isValidate: true,
          isSendMsg: false
        };
        this.btnLoading = true;
        publishOrder(params).then(res => {
          if (res.data && res.data.ids) {
            const loadUserParams = { id: this.orderId };// v2.9.6限制人员仅展示有审核权限的
            loadUserParams.authUrl = 'crm:orderList:examine';
            loadUserParams.perPage = 15;
            let defaultUser = null;// 不回填销售，v2.9.6
            if (localStorage.getItem('publishOrder') !== 'undefined' && JSON.parse(localStorage.getItem('publishOrder'))) {
              defaultUser = JSON.parse(localStorage.getItem('publishOrder'));
            }
            this.$refs.publishDialogRef.showDialog({ defaultMsg: '您有新待审批订单需要处理', defaultObjectUser: defaultUser, loadUserParams });
          }
          this.btnLoading = false;
        }).catch(() => {
          this.btnLoading = false;
        });
      }).catch(_ => ({}));
    },
    toPublish(data) {
      data.id = this.orderId;
      this.btnLoading = true;
      if (data && data.users) { // 通过则缓存
        localStorage.setItem('publishOrder', JSON.stringify(data.users));// 缓存发布步骤的人员
        delete data.users;
      }
      publishOrder(data).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          ElMessage.success('发布成功');
          this.$emit('getInfo');
        } else {
          ElMessage.success(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    // 撤销：待核算, isDraft: 是否撤回到草稿
    revokeDialog({ message, status } = {}) {
      // status  0:草稿中  1:待发布 2:待核算 3:待审批 4:待封账 5:封账中 6:已封账 7:已完成
      const isDraft = status === 0;
      const msg = message || '';
      let defaultObjectUser = [];
      if (!isDraft) {
        if (this.detailInfo && this.detailInfo.orderInfo && this.detailInfo.orderInfo.orderOperator) {
          defaultObjectUser = this.detailInfo.orderInfo.orderOperator;
        }
      } else {
        if (this.detailInfo && this.detailInfo.clientInfo && this.detailInfo.clientInfo.marketId) {
          defaultObjectUser = [{ id: this.detailInfo.clientInfo.marketId, userName: this.detailInfo.clientInfo.market }];
        }
      }
      let isSeal;
      if (this.detailInfo.orderStatus === 4) {
        isSeal = true;
      } else {
        isSeal = false;
      }
      this.$refs.backDialogRef.showDialog({ defaultMsg: msg, defaultObjectUser, extendParams: { status }, isSeal });
    },
    revoke(data) {
      data.id = this.orderId;
      data.currentStatus = this.detailInfo.orderStatus;
      backOrder(data).then(res => {
        if (res.code === 200) {
          ElMessage.success('撤回成功');
          this.$emit('getInfo');
        } else {
          ElMessage.success(res.message);
        }
      });
    },
    // 提交核算成本：待核算
    submitCostDialog() {
      const costBreakdown = this.detailInfo.costBreakdown;
      if (costBreakdown.costConfirm === 0) {
        this.submitSummary = '该订单成本未确认，提交后将自动改为已确认，请确认是否提交？';
      } else {
        this.submitSummary = '';
      }
      this.$refs.submitDialogRef.showDialog({ defaultMsg: '您有新待审批订单需要处理', isSubmitCost: true });
    },
    submitCost(data, selectDataList) {
      // localStorage.setItem('selectDataList', selectDataList);
      data.id = this.orderId.toString();
      data.auditorId = data.receiveUsers;
      submitCost(data).then(res => {
        if (res.code === 200) {
          ElMessage.success('提交成功');
          this.$emit('getInfo');
        } else {
          ElMessage.success(res.message);
        }
      });
    },
    // 审批
    toExamineOrder() {
      const h = this.$createElement;
      const showMobilePage = this.showMobilePage;
      const handelOk = () => {
        this.$refs.resolveBtn && (this.$refs.resolveBtn.loading = true);
        MessageBox.close();
        this.toExamine({
          status: 1,
          receiveUsers: this.detailInfo.clientInfo.marketId,
          isSendMsg: true,
          dingTalkMsg: '恭喜，您的订单已通过审批！',
          // url: `${location.origin}?redirect=${this.$route.path}`
          url: `${location.origin}?redirect=/orderPage/orderdetail/`
        });
      };
      const rejectFun = () => {
        MessageBox.close();
        const defaultUser = [{ id: this.detailInfo.clientInfo.marketId, userName: this.detailInfo.clientInfo.market }];
        if (this.$refs.examineDialogRef) {
          this.$refs.examineDialogRef.showDialog({
            defaultMsg: '您有被退回待发布的订单，请及时处理',
            defaultObjectUser: defaultUser,
            receiveDisabled: true,
            extendParams: { url: `${location.origin}?redirect=/orderPage/orderdetail/` }
          });
        }
      };
      MessageBox.confirm('', '', {
        message: h('p', null, [
          h('div', null, '请确认是否通过该订单审批？ '),
          h('div', { class: 'btns-container' }, [
            h('el-button', { on: { click: handelOk }, class: 'resolve-btn', ref: 'resolveBtn', props: { type: 'primary' }}, '通过 '),
            h('el-button', { on: { click: rejectFun }, class: 'reject-btn' }, '拒绝 '),
            h('el-button', { on: { click: MessageBox.close }, class: 'cancel-btn' }, '暂不审批')
          ])
        ]),
        confirmButtonText: '通过',
        cancelButtonText: '拒绝',
        showClose: false,
        showCancelButton: false,
        showConfirmButton: false,
        type: 'warning',
        lockScroll: false,
        customClass: `del-message del-message-cancel message-box-order ${showMobilePage ? ' mobile-message' : ''}`,
        iconClass: 'del-icon',
        center: true
      });
    },
    toExamine(data = {}) {
      // status: 1: 通过审批 0:审批不通过
      data.ids = this.orderId;
      this.btnLoading = true;
      examineOrder(data).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          ElMessage.success('提交成功');
          this.$emit('getInfo');
        } else {
          ElMessage.success(res.message);
        }
      });
    },
    toBack() {
      const sealingId = Number(this.$route.query.sealingId);
      // 返回封账报告
      const isReport = this.$route.query.isReport;
      if (isReport) {
        this.$router.push({
          name: 'sealingStepsDetail',
          params: { id: sealingId }
        });
        return true;
      }
      // END
      // 区分返回跳转为封账还是订单列表
      const stepId = Number(this.$route.query.stepId) || null;
      if (stepId === 1 || stepId === 2) {
        this.$router.push({
          name: 'sealingStepsDetail',
          params: { id: sealingId }
        });
      } else {
        this.$router.push({
          name: 'allOrder'
        });
      }
    },
    toScoreList() {
      this.$emit('toScoreList');
    },
    goChange() {
      const lastOrderId = this.detailInfo.lastOrderId || this.orderId; // 最终单id
      this.$router.push({
        name: 'editOrder',
        params: { orderId: lastOrderId },
        query: { createOrderType: 'change' }
      });
    },
    toEdit() {
      let sealBillType = '';
      if (this.detailInfo && this.detailInfo.orderInfo) {
        sealBillType = this.detailInfo.orderInfo.sealBillType;
      }
      const query = {
        sealBillType: sealBillType
      };
      if (this.detailInfo.orderStatus === 0) {
        query.draft = 1;
      }
      this.$router.push({
        name: 'editOrder',
        params: { orderId: this.orderId },
        query: query
      });
    },
    getAllDeptList() {
      allDeptlist().then(res => {
        handelDepartmentData(res.data);
        this.allDeptList = res.data;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.empty-btn-style {
  border-color: #406EFF;
  background: #fff;
  color: #406EFF;
}
.center {
  align-items: center;
  position: relative;
  ::v-deep .el-rate {
    margin-right: 10px;
    display: flex;
    align-items: center;
    .el-rate__text {
      color: #333333 !important;
      font-family: DIN Alternate, DIN Alternate-Bold;
      font-weight: 700;
      font-size: 14px;
      line-height: 16px;
      margin-left: 3px;
    }
    .el-rate__item {
      .el-rate__icon {
        font-size: 16px;
        margin-right: 0;
      }
    }
  }
  .score-tip {
    position: absolute;
    bottom: 40px;
    z-index: 2000;
    background-color: #FFF8EA;
    border-radius: 4px;
    font-size: 14px;
    padding: 5px 8px;
    span {
      color: #333;
      font-size: 12px;
    }
    .icon {
      cursor: pointer;
      margin-left: 8px;
      color: #C0C4CC;
      &:hover {
        color: #909399;
      }
    }
    ::v-deep .el-icon-warning {
      color: #E6A23C;
    }
    &.score-tip-mobile {
      position: fixed;
      bottom: 44px;
    }
  }
}
</style>
<style lang="scss">
.message-box-order {
  .el-message-box__btns {
    display: none;
  }
  .el-message-box__content {
    padding-bottom: 0;
    padding-top: 20px;
  }
  .btns-container {
    margin-top: 40px;
    .resolve-btn {
      width: 120px;
      padding: 7px 0;
      background: #406EFF;
      border-radius: 4px;
      font-size: 16px;
      font-weight: 500;
      color: #FFFFFF;
    }
    .reject-btn {
      width: 80px;
      padding: 7px 0;
      font-size: 16px;
      font-weight: 500;
      border-color: #FDF3ED;
      background: #FDF3ED;
      color: #FD8546;
    }
    .cancel-btn {
      width: 80px;
      padding: 7px 0;
      font-size: 16px;
      font-weight: 500;
      border-color: #EFF3FB;
      background: #EFF3FB;
      color: #406EFF;
    }
  }
  &.mobile-message {
    .resolve-btn {
      width: 80px;
    }
  }
}
</style>
